﻿using Newtonsoft.Json;

namespace AutoInternet.Utils;

public class JsonUtil
{
    public static string SerializeObject<T>(T t)
    {
        string json = JsonConvert.SerializeObject(t, Formatting.Indented);
        return json;
    }

    public static T? DeserializeObject<T>(string json)
    {
        T? t = JsonConvert.DeserializeObject<T>(json);
        return t;
    }

    public static async Task<string> ReadJsonFile(string jsonPath)
    {
        FileStream fileStream = new FileStream(jsonPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        StreamReader streamReader = new StreamReader(fileStream);
        string json = await streamReader.ReadToEndAsync();
        streamReader.Close();
        fileStream.Close();
        return json;
    }

    public static async Task<bool> WriteJsonFile(string path, string json)
    {
        FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
        StreamWriter streamWriter = new StreamWriter(fileStream);
        try
        {
            await streamWriter.WriteAsync(json);
        }
        catch (Exception ex)
        {
            ColorConsole.log(ex.Message, ConsoleColor.Red);
            Console.Read();
            return false;
        }
        finally
        {
            streamWriter.Flush();
            fileStream.Flush();
            streamWriter.Close();
            fileStream.Close();
        }

        return true;
    }

    public static async Task<bool> AddMessageToFileAsync(string path, string message)
    {
        StreamWriter streamWriter = File.AppendText(path);
        try
        {
            await streamWriter.WriteLineAsync(message);
        }
        catch (Exception ex)
        {
            ColorConsole.log(ex.Message, ConsoleColor.Red);
            Console.Read();
            return false;
        }
        finally
        {
            streamWriter.Flush();
            streamWriter.Close();
        }

        return true;
    }
}